{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install surya-ocr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from pypdfium2 import PdfDocument, PdfPage\n",
    "from PIL import Image\n",
    "\n",
    "def render_image(page: PdfPage, dpi=300):\n",
    "    image = page.render(\n",
    "        scale=dpi / 72,\n",
    "        draw_annots=False\n",
    "    ).to_pil()\n",
    "    image = image.convert(\"RGB\")\n",
    "    return image\n",
    "\n",
    "def convert_pdf_to_images(pdf_path, output_folder, dpi=300):\n",
    "    pdf_name = os.path.splitext(os.path.basename(pdf_path))[0]\n",
    "    pdf_doc = PdfDocument(pdf_path)\n",
    "    \n",
    "    if not os.path.exists(output_folder):\n",
    "        os.makedirs(output_folder)\n",
    "    \n",
    "    images = []\n",
    "    \n",
    "    for i in range(len(pdf_doc)):\n",
    "        page = pdf_doc[i]\n",
    "        image = render_image(page, dpi)\n",
    "        image_filename = f\"{pdf_name}_page_{i + 1}.png\"\n",
    "        image_path = os.path.join(output_folder, image_filename)\n",
    "        image.save(image_path, \"PNG\")\n",
    "        images.append(image)\n",
    "    \n",
    "    return images\n",
    "\n",
    "# Example usage:\n",
    "pdf_path = \"./pdf_set/10333097.pdf\"\n",
    "output_folder = \"output_images\"\n",
    "images = convert_pdf_to_images(pdf_path, output_folder)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "^C\n"
     ]
    }
   ],
   "source": [
    "!surya_layout ./output_images/ --images --results_dir layout_results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llm-venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
